package com.lw.leetcode.arr.b;

/**
 * Created with IntelliJ IDEA.
 * 6114. 移动片段得到字符串
 *
 * @author liw
 * @version 1.0
 * @date 2022/7/11 9:34
 */
public class CanChange {

    public static void main(String[] args) {
        CanChange test = new CanChange();

        // true
//        String a = "_L__R__R_";
//        String b = "L______RR";

        // false
//        String a = "_L__R__R_";
//        String b = "LR______R";

        // false
//        String a = "_L__R__R_";
//        String b = "_____L_RR";

        // false
        String a = "_L__R__R_L";
        String b = "L______RR_";

        // false
//        String a = "R_L_";
//        String b = "__LR";

        boolean b1 = test.canChange(a, b);
        System.out.println(b1);

    }

    public boolean canChange(String start, String target) {
        int length = start.length();
        int j = 0;
        int count = 0;
        for (int i = 0; i < length; i++) {
            char b = target.charAt(i);
            if (b == '_') {
                count--;
                continue;
            }
            if (b == 'L') {
                boolean f = false;
                while (j < length) {
                    char a = start.charAt(j);
                    if (a == 'L') {
                        j++;
                        if (count < 0) {
                            return false;
                        }
                        f = true;
                        break;
                    } else if (a == 'R') {
                        return false;
                    } else {
                        count++;
                        j++;
                    }
                }
                if (!f) {
                    return false;
                }
                continue;
            }
            boolean f = false;
            while (j < length) {
                char a = start.charAt(j);
                if (a == 'R') {
                    j++;
                    if (count > 0) {
                        return false;
                    }
                    f = true;
                    break;
                }else if (a == 'L') {
                    return false;
                } else {
                    count++;
                    j++;
                }
            }
            if (!f) {
                return false;
            }
        }
        for (int i = j; i < length; i++) {
            char a = start.charAt(i);
            if (a == '_') {
                count++;
            } else {
                return false;
            }
        }
        return count == 0;
    }

}
